﻿using AutoMapper;
using AutoMapper.Internal.Mappers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MySystemSetup.EnumDomain;
using MySystemSetup.IRole;
using MySystemSetup.IRole.Dto;
using MySystemSetup.RBACDomain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TodoApp.Dto;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;

namespace MySystemSetup.Role
{
    public class RoleInfoAppService:ApplicationService,IRoleInfoAppService
    {



        public readonly IRepository<RoleInfo, int> _roleRepository;

        private readonly IRepository<UserRole, int> _userRoleRepository;
        private readonly IRepository<RolePermission, int> _rolePermissionRepository;
 
        public RoleInfoAppService(IRepository<RoleInfo, int> roleRepository, IRepository<UserRole, int> userRoleRepository, IRepository<RolePermission, int> rolePermissionRepository)
        {
            _roleRepository = roleRepository;
            _userRoleRepository = userRoleRepository;
            _rolePermissionRepository = rolePermissionRepository;
        
        }




        /// <summary>
        /// 分页显示角色
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="limit">页容量</param>
        /// <param name="rName">用户名</param>
        /// <returns>统一返回格式</returns>

        public async Task<SzrApiPageResult<RoleShowDto>> GetRoleList(int page, int limit, string? rName)
        {
           var res = await _roleRepository.GetListAsync();
            var rolePerRes = await _rolePermissionRepository.GetListAsync();


          
             

            return new SzrApiPageResult<RoleShowDto>()
            {
                code = 0,
                data = res.WhereIf(rName != null, a => a.RoleName.Contains(rName))
                .Join(rolePerRes, a => a.Id,
                b => b.RoleId, (a, b) => new { a, b }).Select(c => new RoleShowDto()
                {
                    Id = c.a.Id,
                    RoleName = c.a.RoleName,
                    RoleDesc = c.a.RoleDesc,
                    ButtonPermiss = c.b.ButtonPermiss,
                    RoleGrade = c.a.RoleGrade
                }).Skip((page - 1) * limit).Take(limit).ToList(),
                count = res.Count(),
                page = (int) Math.Ceiling( res.Count()*1.0 / limit) 
            };

        }


        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="rId">角色编号</param>
        /// <returns>同意返回格式</returns>
        [UnitOfWork]
        public async Task<SzrApiResult<RoleShowDto>> DeleteRoleAsync(int rId,string? UId)
        {



            //工作单元
            using (var unitOfWork = UnitOfWorkManager.Begin())
            {


                try
                {

                    //用户下的角色列表
                    var userRoleList = await _userRoleRepository.GetListAsync(c => c.UId == UId);

                    //用户下的角色列表
                    var roleList = await _roleRepository.GetListAsync();
                    var res = await _roleRepository.FindAsync(c => c.Id == rId);






                    if (userRoleList.Count() == 0)
                    {

                        return new SzrApiResult<RoleShowDto>()
                        {

                            code = 400,
                            msg = "删除角色等级大于等于当前用户角色等级，无法删除",


                        };
                    }
                    else
                    {

                        //查到当当前用户下的最高等级角色
                        var query = roleList.Join(userRoleList, c => c.Id, c => c.RoleId,
                         (c, c1) => c).OrderBy(c => c.RoleGrade).First();
                        if (query.RoleGrade > res.RoleGrade || query.RoleGrade == res.RoleGrade)
                        {

                            return new SzrApiResult<RoleShowDto>()
                            {

                                code = 400,
                                msg = "删除角色等级大于等于当前用户角色等级，无法删除",


                            };

                        }








                        await _roleRepository.DeleteAsync(res);


                        var rolePerList = await _rolePermissionRepository.GetListAsync(c => c.RoleId == rId);


                        //删除用户角色
                        if (rolePerList != null)
                        {
                            foreach (var item in rolePerList)
                            {


                                await _rolePermissionRepository.DeleteAsync(item.Id);
                            }

                        }





                        //删除用户角色
                        if (userRoleList != null)
                        {

                            foreach (var item in userRoleList)
                            {


                                await _userRoleRepository.DeleteAsync(item.Id);
                            }


                        }



                        //提交
                        await unitOfWork.CompleteAsync();
                        return new SzrApiResult<RoleShowDto>()
                        {

                            code = 200,
                            msg = "删除成功",


                        };


                    }

                 

                }
                catch (Exception)
                {
                      // 如果发生异常，则回滚事务
                unitOfWork.Dispose();

                    throw;
                }

            }
        }



        /// <summary>
        /// 获取角色等级枚举
        /// </summary>
        /// <returns>统一返回格式</returns>
        public async Task<SzrApiResult<RoleShowDto>> GetEnumRoleGrade()
        {


            var list= Enum.GetValues<RoleGrade>().Select(c => new
            {

                Id = (int)c,
                Name = c.ToString()
            }).ToList();


            return new SzrApiResult<RoleShowDto>()
            {

                code = 200,
                data = list
            };

        }


        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="dto">要添加的实体</param>
        /// <returns>统一返回格式</returns>

        public async Task<SzrApiResult<RoleAddDto>> AddRole66666Async(RoleAddDto dto)
        {
            try
            {


                //var database =(await _roleRepository.GetDbContextAsync()).Database;

                //var dbConnection=database.GetDbConnection();


                //StringBuilder sql = new StringBuilder($"select RoleName  from RoleInfo where  RoleName={dto.RoleName}");



                var entity = new RoleInfo();


                entity.RoleName=dto.RoleName;
                entity.RoleDesc=dto.RoleDesc;
                entity.RoleGrade=dto.RoleGrade; 





                var union = await _roleRepository.GetListAsync();


                var role = union.Where(c=>c.RoleName==dto.RoleName).FirstOrDefault();


                if (role != null)
                {
                    return new SzrApiResult<RoleAddDto>()
                    {

                        code = 400,
                        msg = "角色名称重复"
                    };

                }
                //var res = await dbConnection.QueryAsync(

                //用户下的角色列表
                var userRoleList = await _userRoleRepository.GetListAsync(c => c.UId == dto.UId);

                //用户下的角色列表
                var roleList = await _roleRepository.GetListAsync();
               // var res = await _roleRepository.FindAsync(c => c.Id == rId);


                if (userRoleList.Count > 0 && roleList.Count > 0)
                {


                    //查到当当前用户下的最高等级角色
                    var query = roleList.Join(userRoleList, c => c.Id, c => c.RoleId,
                        (c, c1) => c).OrderBy(c => c.RoleGrade).First();




                    if (query.RoleGrade > dto.RoleGrade || query.RoleGrade == dto.RoleGrade)
                    {

                        return new SzrApiResult<RoleAddDto>()
                        {

                            code = 400,
                            msg = "添加的角色等级不能大于等于当前用户角色等级",


                        };

                    }
                }





              //  var res = ObjectMapper.Map<RoleAddDto, RoleInfo>(dto);




                //var list = Enum.GetValues(typeof(RoleGrade)).OfType<RoleGrade>().Select(c => new
                //{

                //    Id = (int)c,
                //    Name = c.ToString()
                //});

                //res.RoleGrade =(RoleGrade)list.FirstOrDefault(c => c.Name == res.RoleGrade.ToString()).Id;
                await _roleRepository.InsertAsync(entity);

                 //var res=   await _userRoleRepository.InsertAsync(new UserRole { UId = "123", RoleId = 1 });

                return new SzrApiResult<RoleAddDto>()
                {

                    code = 200,
                    msg = "添加成功",
                };
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 查询所有角色
        /// </summary>
        /// <returns>统一返回格式</returns>

        public async Task<SzrApiResult<RoleShowDto>> GetRoleListAllAsync(string perId)
        {



            var res= await _roleRepository.GetListAsync();

            var rolePerRes = await _rolePermissionRepository.GetListAsync();


            var query = res.Select(c => new RoleShowDto()
            {
                Id = c.Id,
                RoleName = c.RoleName,
                ButtonPermiss = rolePerRes.Where(c1 => c1.RoleId == c.Id&&c1.PermissId==perId).Select(c2 => c2.ButtonPermiss).FirstOrDefault(),
            }).ToList();



            return new SzrApiResult<RoleShowDto>()
            {

                code = 0,
                data = query
            };
            


        }


        /// <summary>
        /// 查询改用户可添加的角色
        /// </summary>
        /// <returns>统一返回格式</returns>

        public async Task<SzrApiResult<RoleShowDto>> GetRoleUserAllAsync(string uId)
        {

            //用户下的角色列表
            var userRoleList = await _userRoleRepository.GetListAsync(c => c.UId == uId);

            //用户下的角色列表
            var roleList = await _roleRepository.GetListAsync();
            // var res = await _roleRepository.FindAsync(c => c.Id == rId);


            if (userRoleList.Count > 0 && roleList.Count > 0)
            {


                //查到当当前用户下的最高等级角色
                var query = roleList.Join(userRoleList, c => c.Id, c => c.RoleId,
                    (c, c1) => c).OrderBy(c => c.RoleGrade).First();

                var res = await _roleRepository.GetListAsync(c => c.RoleGrade > query.RoleGrade);


                return new SzrApiResult<RoleShowDto>()
                {

                    code = 0,
                    data = res.Select(c => new RoleShowDto()
                    {
                        Id = c.Id,
                        RoleName = c.RoleName,
                      
                    }).ToList()
                };
                

            }

            return new SzrApiResult<RoleShowDto>()
            {

                code = 400,
                msg = "当前用户没有可添加的角色"
            };
            
             

        }
    }
}
